package com.example.cofeed.activity;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.ada.common.util.CustomHelper;
import com.baoyz.actionsheet.ActionSheet;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.ObjectUtils;
import  com.example.cofeed.util.ToastUtils;;
import com.example.cofeed.R;
import com.example.cofeed.adapter.SelectPhotoAdapter;
import com.example.cofeed.api.ApiService;
import com.example.cofeed.base.TakePhotoActivity;
import com.example.cofeed.callback.DialogCallback;
import com.example.cofeed.callback.LzyResponse;
import com.example.cofeed.constant.IntentKeyConstant;
import com.example.cofeed.entity.Supply;
import com.lzy.okgo.model.Response;
import com.umeng.analytics.MobclickAgent;

import org.devio.takephoto.model.TResult;

import java.io.File;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class DemandIssueActivity extends TakePhotoActivity {
    @BindView(R.id.et_title)
    EditText mEtTitle;
    @BindView(R.id.tv_breed)
    TextView mTvBreed;
    @BindView(R.id.tv_type)
    TextView mTvType;
    @BindView(R.id.et_num)
    EditText mEtNum;
    @BindView(R.id.et_pick_place)
    EditText mEtPickPlace;
    @BindView(R.id.et_specification)
    EditText mEtSpecification;
    @BindView(R.id.et_factory)
    EditText mEtFactory;
    @BindView(R.id.rv_photo)
    RecyclerView mRvPhoto;
    @BindView(R.id.et_content)
    EditText mEtContent;
    @BindView(R.id.confirm_tv)
    TextView mConfirmTv;
    @BindView(R.id.rb_contact)
    CheckBox mRbContact;
    @BindView(R.id.et_company)
    EditText mEtCompany;
    @BindView(R.id.et_phone)
    EditText mEtPhone;
    @BindView(R.id.et_contact)
    EditText mEtContact;
    @BindView(R.id.et_price)
    EditText mEtPrice;
    @BindView(R.id.layout_contact)
    LinearLayout mLayoutContact;
    private SelectPhotoAdapter mSelectPhotoAdapter;
    //    private int mCatId;
    private int mId;
    private int mBreedId;
    final String[] items = {"供应", "求购", "招商", "招聘"};
    private int mDemandId;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_demand_issue;
    }

    @Override
    protected void init(Bundle savedInstanceState, View container) {
        setMainTitle("供求发布");

        mDemandId = getIntent().getIntExtra(IntentKeyConstant.DEMAND_ID, 0);

        mRbContact.setOnCheckedChangeListener((buttonView, isChecked) -> {
            if (isChecked) {
                mLayoutContact.setVisibility(View.VISIBLE);
            } else {
                mLayoutContact.setVisibility(View.GONE);
            }
        });

//        mCatId = getIntent().getIntExtra(IntentKeyConstant.CAT_ID, 0);
        mId = getIntent().getIntExtra(IntentKeyConstant.ID, 0);
        mType = getIntent().getIntExtra(IntentKeyConstant.TYPE, 0);

        if (mType > 0) {
            mTvType.setText(items[mType - 1]);

        }

        if (mDemandId > 0) {
            ApiService.supply_edit(this, mDemandId, new DialogCallback<LzyResponse<Supply>>(this) {
                @Override
                public void onSuccess(Response<LzyResponse<Supply>> response) {
                    Supply supply = response.body().data;

                    mId = mDemandId;
                    mBreedId = supply.catid;

                    mEtTitle.setText(supply.title);
                    mTvBreed.setText(supply.catname);

                    if (supply.stype > 0){
                        mTvType.setText(items[supply.stype - 1]);
                    }
                    mEtNum.setText(supply.number);
                    mEtSpecification.setText(supply.material);
                    mEtFactory.setText(supply.product);
                    mEtPrice.setText(supply.price);
                    mEtPickPlace.setText(supply.pick_place);
                    mEtContent.setText(supply.content);

                    mSelectPhotoAdapter.setNewData(supply.imgsrc);

                    mEtCompany.setText(supply.company);
                    mEtPhone.setText(supply.tel);
                    mEtContact.setText(supply.linkman);

                }
            });
        }

        mSelectPhotoAdapter = new SelectPhotoAdapter();
        LinearLayoutManager horManager = new GridLayoutManager(this, 3);

        mRvPhoto.setLayoutManager(horManager);
        mRvPhoto.setAdapter(mSelectPhotoAdapter);

        mSelectPhotoAdapter.addData("");

        mSelectPhotoAdapter.setOnItemClickListener((adapter, view, position) -> {
            if (adapter.getData().size() > 9) {
                ToastUtils.showShort("最多可以选择9张图片");
                return;
            }
            if (position == adapter.getItemCount() - 1) {
                showActionSheet();
            }
        });

        mSelectPhotoAdapter.setOnItemChildClickListener((adapter, view, position) -> {
            mSelectPhotoAdapter.remove(position);

        });

    }

    private void showActionSheet() {
        setTheme(R.style.ActionSheetStyleiOS7);
        ActionSheet
                .createBuilder(this, getSupportFragmentManager())
                .setCancelButtonTitle("取消")
                .setOtherButtonTitles("拍照", "从相册选择").setCancelableOnTouchOutside(true)
                .setListener(new ActionSheet.ActionSheetListener() {
                    @Override
                    public void onDismiss(ActionSheet actionSheet, boolean isCancel) {

                    }

                    @Override
                    public void onOtherButtonClick(ActionSheet actionSheet, int index) {
                        switch (index) {
                            case 0:
                                CustomHelper.TakePhoto(getTakePhoto(), CustomHelper.PICK_BY_TAKE, false);
                                break;
                            case 1:
                                CustomHelper.TakePhoto(getTakePhoto(), CustomHelper.PICK_BY_SELECT, false);
                                break;
                            default:
                        }
                    }
                }).show();

    }

    @Override
    public void takeSuccess(TResult result) {
        super.takeSuccess(result);
        ApiService.uploader(this, new File(result.getImage().getCompressPath()), new DialogCallback<LzyResponse<Map<String, String>>>() {
            @Override
            public void onSuccess(Response<LzyResponse<Map<String, String>>> response) {
                String imgsrc = Uri.decode(response.body().data.get("imgsrc"));
                mSelectPhotoAdapter.addData(mSelectPhotoAdapter.getItemCount() - 1, imgsrc);

            }
        });

    }


    private int mType = 0;

    @OnClick({R.id.tv_breed, R.id.tv_type, R.id.confirm_tv})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_breed:
                Intent intent = new Intent(this, BreedSelectActivity.class);
                startActivityForResult(intent, 3);
                break;
            case R.id.tv_type:

                AlertDialog.Builder builder = new AlertDialog.Builder(this);
                //builder.setIcon(R.drawable.ic_launcher);
                builder.setTitle("请选择类型");
                //    指定下拉列表的显示数据
                //    设置一个下拉的列表选择项
                builder.setItems(items, (dialog, which) -> {
                    mType = which + 1;
                    mTvType.setText(items[which]);

                });
                builder.show();


                break;
            case R.id.confirm_tv:

                String title = mEtTitle.getText().toString().trim();
                String breed = mTvBreed.getText().toString().trim();
                String type = mTvType.getText().toString().trim();
                String num = mEtNum.getText().toString().trim();
                String specification = mEtSpecification.getText().toString().trim();
                String factory = mEtFactory.getText().toString().trim();
                String price = mEtPrice.getText().toString().trim();
                String pickPlace = mEtPickPlace.getText().toString().trim();

                String content = mEtContent.getText().toString().trim();

                if (ObjectUtils.isEmpty(title)) {
                    ToastUtils.showShort("请输入标题");
                    return;
                }
                if (ObjectUtils.isEmpty(breed)) {
                    ToastUtils.showShort("请选择品种");
                    return;
                }
                if (ObjectUtils.isEmpty(type)) {
                    ToastUtils.showShort("请选择类型");
                    return;
                }
                if (ObjectUtils.isEmpty(num)) {
                    ToastUtils.showShort("请输入数量");
                    return;
                }
//                if (ObjectUtils.isEmpty(specification)) {
//                    ToastUtils.showShort("请输入质量或规格");
//                    return;
//                }
                if (ObjectUtils.isEmpty(factory)) {
                    ToastUtils.showShort("请输入厂家或产地");
                    return;
                }
//                if (ObjectUtils.isEmpty(price)) {
//                    ToastUtils.showShort("请输入价格");
//                    return;
//                }
                if (ObjectUtils.isEmpty(pickPlace)) {
                    ToastUtils.showShort("请输入提货地");
                    return;
                }
//                if (mSelectPhotoAdapter.getItemCount() == 1) {
//                    ToastUtils.showShort("请选择图片");
//                    return;
//                }
                if (ObjectUtils.isEmpty(content)) {
                    ToastUtils.showShort("请输入内容");
                    return;
                }
                String company = "";
                String phone = "";
                String contact = "";
                if (mRbContact.isChecked()) {
                    company = mEtCompany.getText().toString().trim();
                    phone = mEtPhone.getText().toString().trim();
                    contact = mEtContact.getText().toString().trim();

                    if (ObjectUtils.isEmpty(company)) {
                        ToastUtils.showShort("请输入公司名称");
                        return;
                    }
                    if (ObjectUtils.isEmpty(phone)) {
                        ToastUtils.showShort("请输入手机号");
                        return;
                    }
                    if (ObjectUtils.isEmpty(contact)) {
                        ToastUtils.showShort("请输入联系人");
                        return;
                    }
                }


                ApiService.supply_save(this,
                        title,
                        content,
                        mBreedId,
                        mId,
                        mSelectPhotoAdapter.getData().subList(0, mSelectPhotoAdapter.getItemCount() - 1),
                        company,
                        specification,
                        num,
                        contact,
                        phone,
                        factory,
                        mType,
                        price,
                        pickPlace, new DialogCallback<LzyResponse<Object>>(DemandIssueActivity.this) {
                            @Override
                            public void onSuccess(Response<LzyResponse<Object>> response) {
                                showToast();
                                setResult(RESULT_OK);
                                Intent intent = getIntent();
                                finish();
                                startActivity(intent);
//                                finish();
                            }
                        });

                break;
                default:
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == 3) {
                mBreedId = data.getIntExtra(IntentKeyConstant.ID, 0);
                String name = data.getStringExtra(IntentKeyConstant.NAME);
                String firstStr = data.getStringExtra(IntentKeyConstant.FIRST_STR);
                mTvBreed.setText(firstStr);
                mEtSpecification.setText(name);

            }
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        MobclickAgent.onResume(this);
    }

    @Override
    public void onPause() {
        super.onPause();
        MobclickAgent.onPause(this);
    }

}
